{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Validate IP Address"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Medium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #string"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #字符串"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: validIPAddress"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #验证IP地址"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>给定一个字符串&nbsp;<code>queryIP</code>。如果是有效的 IPv4 地址，返回 <code>\"IPv4\"</code> ；如果是有效的 IPv6 地址，返回 <code>\"IPv6\"</code> ；如果不是上述类型的 IP 地址，返回 <code>\"Neither\"</code> 。</p>\n",
    "\n",
    "<p><strong>有效的IPv4地址</strong> 是 <code>“x1.x2.x3.x4”</code> 形式的IP地址。 其中&nbsp;<code>0 &lt;= x<sub>i</sub>&nbsp;&lt;= 255</code>&nbsp;且&nbsp;<code>x<sub>i</sub></code>&nbsp;<strong>不能包含</strong> 前导零。例如:&nbsp;<code>“192.168.1.1”</code>&nbsp;、 <code>“192.168.1.0”</code> 为有效IPv4地址， <code>“192.168.01.1”</code> 为无效IPv4地址; <code>“192.168.1.00”</code> 、 <code>“192.168@1.1”</code> 为无效IPv4地址。</p>\n",
    "\n",
    "<p><strong>一个有效的IPv6地址&nbsp;</strong>是一个格式为<code>“x1:x2:x3:x4:x5:x6:x7:x8”</code> 的IP地址，其中:</p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>1 &lt;= x<sub>i</sub>.length &lt;= 4</code></li>\n",
    "\t<li><code>x<sub>i</sub></code>&nbsp;是一个 <strong>十六进制字符串</strong> ，可以包含数字、小写英文字母( <code>'a'</code> 到 <code>'f'</code> )和大写英文字母( <code>'A'</code> 到 <code>'F'</code> )。</li>\n",
    "\t<li>在&nbsp;<code>x<sub>i</sub></code>&nbsp;中允许前导零。</li>\n",
    "</ul>\n",
    "\n",
    "<p>例如 <code>\"2001:0db8:85a3:0000:0000:8a2e:0370:7334\"</code> 和 <code>\"2001:db8:85a3:0:0:8A2E:0370:7334\"</code> 是有效的 IPv6 地址，而 <code>\"2001:0db8:85a3::8A2E:037j:7334\"</code> 和 <code>\"02001:0db8:85a3:0000:0000:8a2e:0370:7334\"</code> 是无效的 IPv6 地址。</p>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>示例 1：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>queryIP = \"172.16.254.1\"\n",
    "<strong>输出：</strong>\"IPv4\"\n",
    "<strong>解释：</strong>有效的 IPv4 地址，返回 \"IPv4\"\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 2：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>queryIP = \"2001:0db8:85a3:0:0:8A2E:0370:7334\"\n",
    "<strong>输出：</strong>\"IPv6\"\n",
    "<strong>解释：</strong>有效的 IPv6 地址，返回 \"IPv6\"\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 3：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>queryIP = \"256.256.256.256\"\n",
    "<strong>输出：</strong>\"Neither\"\n",
    "<strong>解释：</strong>既不是 IPv4 地址，又不是 IPv6 地址\n",
    "</pre>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>queryIP</code> 仅由英文字母，数字，字符 <code>'.'</code> 和 <code>':'</code> 组成。</li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [validate-ip-address](https://leetcode.cn/problems/validate-ip-address/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [validate-ip-address](https://leetcode.cn/problems/validate-ip-address/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['\"172.16.254.1\"', '\"2001:0db8:85a3:0:0:8A2E:0370:7334\"', '\"256.256.256.256\"']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, queryIP: str) -> str:\n",
    "        if self.isIPv4(queryIP):\n",
    "            return \"IPv4\"\n",
    "        if self.isIPv6(queryIP):\n",
    "            return \"IPv6\"\n",
    "        return \"Neither\"\n",
    "    def isIPv4(self, query):\n",
    "        queries = query.split('.')\n",
    "        if len(queries) != 4:\n",
    "            return False\n",
    "        for seg in queries:\n",
    "            if not seg.isdigit():\n",
    "                return False\n",
    "            if seg[0] == '0' and len(seg) > 1:\n",
    "                return False\n",
    "            if int(seg) > 255:\n",
    "                return False\n",
    "        return True\n",
    "    def isIPv6(self, query):\n",
    "        queries = query.split(':')\n",
    "        letters = {'a', 'b', 'c', 'd', 'e', 'f'}\n",
    "        if len(queries) != 8:\n",
    "            return False\n",
    "        for seg in queries:\n",
    "            if len(seg) == 0 or len(seg) > 4:\n",
    "                return False\n",
    "            for s in seg:\n",
    "                if not s.isdigit() and s.lower() not in letters:\n",
    "                    return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP):\n",
    "        \"\"\"\n",
    "        :type IP: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        def isIPv4(s):\n",
    "            try:\n",
    "                return str(int(s))==s and 0<=int(s)<=255\n",
    "            except:\n",
    "                return False\n",
    "            \n",
    "        def isIPv6(s):\n",
    "            if len(s)>4:\n",
    "                return False\n",
    "            try:\n",
    "                return int(s,16)>=0 and s[0]!='-'\n",
    "            except:\n",
    "                return False\n",
    "            \n",
    "        if IP.count(\".\")==3 and all(isIPv4(i) for i in IP.split(\".\")):\n",
    "            return \"IPv4\"\n",
    "        if IP.count(\":\")==7 and all(isIPv6(i) for i in IP.split(\":\")):\n",
    "            return \"IPv6\"\n",
    "        return \"Neither\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP):\n",
    "        \"\"\"\n",
    "        :type IP: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        if self.validIPV4(IP):\n",
    "            return 'IPv4'\n",
    "        if self.validIPV6(IP):\n",
    "            return 'IPv6'\n",
    "        return 'Neither'\n",
    "\n",
    "    def validIPV4(self, IP):\n",
    "        parts = IP.split('.')\n",
    "        if len(parts) != 4: return False\n",
    "        for part in parts:\n",
    "            if not part: return False\n",
    "            if not part.isdigit(): return False\n",
    "            if part[0] == '0' and len(part) > 1: return False\n",
    "            if int(part) > 255: return False\n",
    "        return True\n",
    "\n",
    "    def validIPV6(self, IP):\n",
    "        parts = IP.split(':')\n",
    "        if len(parts) != 8: return False\n",
    "        for part in parts:\n",
    "            if not part: return False\n",
    "            if len(part) > 4: return False\n",
    "            if any(c not in string.hexdigits for c in part): return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import re\n",
    "ipv4 = re.compile(r'^(\\d{1,3}\\.){3}\\d{1,3}$')\n",
    "ipv6= re.compile(r'^([a-fA-F\\d]{1,4}\\:){7}[a-fA-F\\d]{1,4}$')\n",
    "         \n",
    "                                   \n",
    "class Solution:\n",
    "    def validIPAddress(self, IP):\n",
    "        \"\"\"\n",
    "        :type IP: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        if ipv4.match(IP):\n",
    "            li = IP.split('.')\n",
    "            for i in li:\n",
    "                if (i!='0' and i.startswith('0')) or int(i)>255:\n",
    "                    return 'Neither' \n",
    "            return 'IPv4'\n",
    "        elif ipv6.match(IP):\n",
    "            return 'IPv6'\n",
    "        else:\n",
    "            return 'Neither'\n",
    "            \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP: str) -> str:\n",
    "        if '.' in IP:\n",
    "            for ip in IP:\n",
    "                if ip.isdigit() or ip=='.':\n",
    "                    continue\n",
    "                return 'Neither'\n",
    "            s_IP4=IP.split('.')\n",
    "            if len(s_IP4)!=4:\n",
    "                return 'Neither'\n",
    "            for s in s_IP4:\n",
    "                if (not s) or (s!='0' and s.lstrip('0')!=s) or (int(s)<0) or (int(s)>255):\n",
    "                    return 'Neither'\n",
    "            return 'IPv4'\n",
    "        elif ':' in IP:\n",
    "            for ip in IP:\n",
    "                if ip.isalnum() or ip==':':\n",
    "                    continue\n",
    "                return 'Neither'\n",
    "            s_IP6=IP.split(':')\n",
    "            valid=set(['a','b','c','d','e','f'])\n",
    "            if len(s_IP6)!=8:\n",
    "                return 'Neither'\n",
    "            for s in s_IP6:\n",
    "                if not s or len(s)>4:\n",
    "                    return 'Neither'\n",
    "                for ss in s:\n",
    "                    if ss.isalpha() and ss.lower() not in valid:\n",
    "                        return 'Neither'\n",
    "            return 'IPv6'\n",
    "        return 'Neither'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP: str) -> str:\n",
    "\n",
    "        def checkIPv4(IP):\n",
    "            nums = IP.split(\".\")\n",
    "            if len(nums) != 4:\n",
    "                return False\n",
    "            for num in nums:\n",
    "                if not num or (not num.isdecimal()) or (num[0] == '0' and len(num) != 1) or int(num) > 255:\n",
    "                    return False\n",
    "            return True\n",
    "        \n",
    "        def checkIPv6(IP):\n",
    "            IP = IP.lower()\n",
    "            if \"::\" in IP:\n",
    "                return False\n",
    "            nums = IP.split(\":\")\n",
    "            valid = \"0123456789abcdef\"\n",
    "            # print(nums)\n",
    "            if len(nums) != 8:\n",
    "                return False\n",
    "            for num in nums:\n",
    "                if not num: \n",
    "                    continue\n",
    "                if len(num) >= 5: \n",
    "                    return False\n",
    "                for n in num:\n",
    "                    if n not in valid:\n",
    "                        return False\n",
    "            return True\n",
    "        \n",
    "        if checkIPv4(IP):\n",
    "            return \"IPv4\"\n",
    "        elif checkIPv6(IP):\n",
    "            return \"IPv6\"\n",
    "        else:\n",
    "            return \"Neither\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP: str) -> str:\n",
    "        if '.' in IP:\n",
    "            ip_list = IP.split('.')\n",
    "            length = len(ip_list)\n",
    "\n",
    "            if length == 4:\n",
    "                for ip in ip_list:\n",
    "                    if not ip.isdigit():\n",
    "                        return 'Neither'\n",
    "                    if 0 <= int(ip) <= 255:\n",
    "                        if str(int(ip)) != ip:\n",
    "                            return 'Neither'\n",
    "                    else:\n",
    "                        return 'Neither'\n",
    "\n",
    "                return 'IPv4'\n",
    "            \n",
    "        if ':' in IP:\n",
    "            ip_list = IP.split(':')\n",
    "            \n",
    "            if len(ip_list) == 8:\n",
    "                if '' in ip_list:\n",
    "                    return 'Neither'\n",
    "\n",
    "                for ip in ip_list:\n",
    "                    if len(ip) > 4:\n",
    "                        return 'Neither'\n",
    "                    for s in ip:\n",
    "                        if s.upper() > 'F' or (s.isdigit() == False and s.isalpha() == False):\n",
    "                            return 'Neither'\n",
    "                \n",
    "                return 'IPv6'\n",
    "\n",
    "        return 'Neither'\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP: str) -> str:\n",
    "        try:\n",
    "            if IP.count('.') == 3:\n",
    "                a, b, c, d = IP.split('.')\n",
    "                if evaluate_ipv4(a) and evaluate_ipv4(b) and evaluate_ipv4(c) and evaluate_ipv4(d):\n",
    "                    return 'IPv4'\n",
    "            elif IP.count(':') == 7:\n",
    "                a, b, c, d, e, f, g, h = IP.split(':')\n",
    "                if evaluate_ipv6(a) and evaluate_ipv6(b) and evaluate_ipv6(c) and evaluate_ipv6(d) and evaluate_ipv6(e) and evaluate_ipv6(f) and evaluate_ipv6(g) and evaluate_ipv6(h):\n",
    "                    return 'IPv6'\n",
    "        except:\n",
    "            pass\n",
    "        return 'Neither'\n",
    "\n",
    "\n",
    "\n",
    "def evaluate_ipv4(a):\n",
    "    return a == str(int(a)) and 0<= int(a) <= 255\n",
    "\n",
    "def evaluate_ipv6(a):\n",
    "    valid_c = '1234567890abcdefABCDEF'\n",
    "\n",
    "    if not 0 < len(a) <= 4:\n",
    "        return False\n",
    "\n",
    "    for c in a:\n",
    "        if c not in valid_c:\n",
    "            return False\n",
    "\n",
    "    return True\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP: str) -> str:\n",
    "        if '.' in IP:\n",
    "            # val ipv4\n",
    "            ips = IP.split('.')\n",
    "            if len(ips) != 4:\n",
    "                return \"Neither\"\n",
    "            for a in ips:\n",
    "                try:\n",
    "                    if a[0]=='0' and len(a) != 1:\n",
    "                        return \"Neither\" \n",
    "                    elif int(a) <0 or int(a) > 255:\n",
    "                        return \"Neither\"\n",
    "                except:\n",
    "                    return \"Neither\"\n",
    "            return \"IPv4\"\n",
    "\n",
    "        elif ':' in IP:\n",
    "            ips = IP.split(':')\n",
    "            if len(ips) != 8:\n",
    "                return \"Neither\"\n",
    "            # val ipv6\n",
    "            for a in ips:\n",
    "                if len(a) == 0 or len(a) > 4:\n",
    "                    return \"Neither\"\n",
    "                for aa in a:\n",
    "                    if aa not in '0123456789abcdefABCDEF':\n",
    "                        return \"Neither\"\n",
    "            return \"IPv6\"\n",
    "        return \"Neither\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP: str) -> str:\n",
    "        def v4(IP):\n",
    "            x = IP.split('.')\n",
    "            if len(x) != 4:\n",
    "                return 'Neither'\n",
    "            for i in x:\n",
    "                if len(i)==0 or (i[0] == '0' and len(i) > 1):\n",
    "                    return 'Neither'\n",
    "                elif not i.isdigit() or int(i) < 0 or int(i) > 255:\n",
    "                    return 'Neither'\n",
    "            return 'IPv4'\n",
    "\n",
    "        def v6(IP):\n",
    "            x = IP.split(':')\n",
    "            if len(x) != 8:\n",
    "                return 'Neither'\n",
    "            m = '0123456789abcdefABCDEF'\n",
    "            for s in x:\n",
    "                if len(s) == 0 or len(s) > 4:\n",
    "                    return 'Neither'\n",
    "                for ch in s:\n",
    "                    if ch not in m:\n",
    "                        return 'Neither'\n",
    "            return 'IPv6'\n",
    "        if '.' in IP:\n",
    "            return v4(IP)\n",
    "        if ':' in IP:\n",
    "            return v6(IP)\n",
    "        return 'Neither'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP: str) -> str:\n",
    "        if '.' in IP:\n",
    "            ips = IP.split('.')\n",
    "            if len(ips) != 4:\n",
    "                return 'Neither'\n",
    "            else:\n",
    "                for a in ips:\n",
    "                    #print(a)\n",
    "                    try:\n",
    "                        if a.startswith('0') and len(a) != 1:\n",
    "                            return 'Neither'\n",
    "                        elif int(a) < 0 or int(a) > 255:\n",
    "                            return 'Neither'\n",
    "                    except:\n",
    "                        return 'Neither'\n",
    "                return \"IPv4\"\n",
    "        elif ':' in IP:\n",
    "            ips = IP.split(':')\n",
    "            if len(ips) != 8:\n",
    "                return 'Neither'\n",
    "            else:\n",
    "                for a in ips:\n",
    "                    if len(a) == 0 or len(a) > 4:\n",
    "                        return 'Neither'\n",
    "                    for i in a:\n",
    "                        if i not in list('1234567890abcdefABCDEF'):\n",
    "                            return 'Neither'\n",
    "                return 'IPv6'\n",
    "        return 'Neither'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP: str) -> str:\n",
    "        def is_ipv4(s):\n",
    "            parts = s.split('.')\n",
    "            return len(parts) == 4 and \\\n",
    "                   all(p and all(\"0\" <= c <= \"9\" for c in p) and\n",
    "                       (p == \"0\" or p[0] != \"0\")\n",
    "                       and 0 <= int(p) <= 255\n",
    "                       for p in parts)\n",
    "\n",
    "        def is_ipv6(s):\n",
    "            parts = s.split(':')\n",
    "            return len(parts) == 8 and \\\n",
    "                   all(p and len(p) <= 4 and\n",
    "                       all(\"0\" <= c <= \"9\" or \"a\" <= c <= \"f\" or \"A\" <= c <= \"F\"\n",
    "                           for c in p)\n",
    "                       for p in parts)\n",
    "\n",
    "        if is_ipv4(IP):\n",
    "            return \"IPv4\"\n",
    "        elif is_ipv6(IP):\n",
    "            return \"IPv6\"\n",
    "        else:\n",
    "            return \"Neither\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, IP: str) -> str:\n",
    "        if '.' not in IP and ':' not in IP: return 'Neither'\n",
    "        p_char,p_ipv6=re.compile('[a-fA-F]+'),re.compile('[\\da-fA-F]+|0')\n",
    "        if '.' in IP :\n",
    "            if ':' in IP: return 'Neither'\n",
    "            arr=IP.split('.')\n",
    "            if len(arr)!=4: return 'Neither'\n",
    "            else:\n",
    "                for item in arr:\n",
    "                    if len(item)==0: return 'Neither'\n",
    "                    elif len(p_char.findall(item))>0: return 'Neither'\n",
    "                    elif re.match('0\\d+',item) is not None: return 'Neither'\n",
    "                    elif int(item) not in range(0,256): return 'Neither'\n",
    "            return 'IPv4'\n",
    "        if ':' in IP:\n",
    "            if '.' in IP: return 'Neither'\n",
    "            arr=IP.split(':')\n",
    "            if len(arr)!=8: return 'Neither'\n",
    "            else:\n",
    "                for item in arr:\n",
    "                    if len(item)>4 or len(item)==0: return 'Neither'\n",
    "                    else:\n",
    "                        temp=p_ipv6.findall(item)\n",
    "                        if len(temp)<1: return 'Neither'\n",
    "                        elif temp[-1] !=item: return 'Neither'\n",
    "                return 'IPv6'\n",
    "\n",
    "\n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, queryIP: str) -> str:\n",
    "        if queryIP.find('.') != -1:\n",
    "            last = -1\n",
    "            for i in range(4):\n",
    "                if i == 3:\n",
    "                    cur = len(queryIP)\n",
    "                else:\n",
    "                    cur = queryIP.find('.', last+1)\n",
    "                    print('cur=', cur)\n",
    "            \n",
    "                if cur == -1:\n",
    "                    return 'Neither'\n",
    "                if not 1 <= cur-last-1 <= 3:\n",
    "                    print(last, cur)\n",
    "                    return 'Neither'\n",
    "                \n",
    "                address = 0\n",
    "                for j in range(last+1, cur):\n",
    "                    if not queryIP[j].isdigit():\n",
    "                        return 'Neither'\n",
    "\n",
    "                    address = address*10 + int(queryIP[j])\n",
    "                \n",
    "                if address > 255:\n",
    "                    return 'Neither'\n",
    "                if address == 0 and cur-last-1>1:\n",
    "                    return 'Neither'\n",
    "                if address > 0 and queryIP[last+1] == '0':\n",
    "                    return 'Neither'\n",
    "        \n",
    "                last = cur\n",
    "            return 'IPv4'\n",
    "        elif queryIP.find(':') != -1:\n",
    "            last = -1\n",
    "            for i in range(8):\n",
    "                if i == 7:\n",
    "                    cur = len(queryIP)\n",
    "                else:\n",
    "                    cur = queryIP.find(':', last+1)\n",
    "\n",
    "                if cur == -1:\n",
    "                    return 'Neither'\n",
    "                if not 1 <= cur-last-1 <= 4:\n",
    "                    return 'Neither'\n",
    "                \n",
    "                for j in range(last+1, cur):\n",
    "                    if not queryIP[j].isdigit() and not 'a' <= queryIP[j].lower() <= 'f':\n",
    "                        return 'Neither'\n",
    "            \n",
    "                last = cur\n",
    "\n",
    "            return 'IPv6'\n",
    "        else:\n",
    "            return 'Neither'\n",
    "                    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, ip: str) -> str:\n",
    "        def check_ip4(x):\n",
    "            if x.isdigit() and 0<=int(x)<=255 and (x=='0' or x[0]!='0'):\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "        def check_ip6(x):\n",
    "            s = '0123456789abcdefABCDEF'\n",
    "            if 1<=len(x)<=4:\n",
    "                for c in x:\n",
    "                    if c not in s:\n",
    "                        return False\n",
    "                return True\n",
    "            return False\n",
    "\n",
    "        if ip.count('.')==3 and all(check_ip4(x) for x in ip.split('.')):\n",
    "            return 'IPv4'\n",
    "        if ip.count(':')==7 and all(check_ip6(x) for x in ip.split(':')):\n",
    "            return 'IPv6'\n",
    "        return 'Neither'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    # 判断是不是有效的IP\n",
    "    def validIPAddress(self, queryIP: str) -> str:\n",
    "\n",
    "        # 判断是不是ipv4\n",
    "        def validIPv4(self,queryIP:str):\n",
    "            list_ip = queryIP.split('.')\n",
    "            if len(list_ip)!=4:\n",
    "                return False\n",
    "            for ip in list_ip:\n",
    "                #判断ipv4\n",
    "                if not ip.isnumeric() or not 0 <=int(ip)<=255:\n",
    "                    return False\n",
    "                #排除前导零\n",
    "                if str(int(ip))!=ip:\n",
    "                    return False\n",
    "            \n",
    "                \n",
    "            return True\n",
    "\n",
    "        #判断是不是ipv6\n",
    "        def validIPv6(self,queryIP):\n",
    "            list_ip = queryIP.split(':')\n",
    "            if len(list_ip)!=8:\n",
    "                return False\n",
    "            for ip in list_ip:\n",
    "                if not 1<=len(ip)<=4:\n",
    "                    return False\n",
    "                for char in ip:\n",
    "                    if not ('0' <= char <= '9' or 'a' <= char <= 'f' or 'A' <= char <= 'F'):\n",
    "                        return False\n",
    "\n",
    "            return True\n",
    "\n",
    "        for char in queryIP[:5]:\n",
    "            if char == '.':\n",
    "                return 'IPv4' if validIPv4(self,queryIP) else 'Neither'\n",
    "            elif char == ':':\n",
    "                return 'IPv6' if validIPv6(self,queryIP) else 'Neither'\n",
    "\n",
    "        return 'Neither'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, queryIP: str) -> str:\n",
    "        sq = queryIP.split('.')\n",
    "        v6 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f'}\n",
    "        if queryIP.count('.') == 3 and len(sq) == 4:\n",
    "            for i in sq:\n",
    "                if not i or (len(i) > 1 and i[0] == '0') or not (i.isdigit() and 0 <= int(i) <= 255):\n",
    "                    break\n",
    "            else:\n",
    "                return 'IPv4'\n",
    "        elif queryIP.count(':') == 7 and len(sq) == 1:\n",
    "            sq = queryIP.split(':')\n",
    "            if len(sq) == 8:\n",
    "                for i in sq:\n",
    "                    if not i or len(i) > 4 or any(j not in v6 for j in i): break\n",
    "                else:\n",
    "                    return 'IPv6'\n",
    "        return 'Neither'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from curses.ascii import isdigit\r\n",
    "from re import T\r\n",
    "\r\n",
    "\r\n",
    "class Solution:\r\n",
    "    def validIPAddress(self, queryIP: str) -> str:\r\n",
    "        alph = ['a','b','c','d','e','f','A','B','C','D','E','F']\r\n",
    "        res = True\r\n",
    "        strList = queryIP.split('.')\r\n",
    "        length = len(strList)\r\n",
    "        if length==4:\r\n",
    "            tempA = 0\r\n",
    "            for i in strList:\r\n",
    "                tempA+=1\r\n",
    "                isFirst = True\r\n",
    "                for j in i:\r\n",
    "                    if isFirst:\r\n",
    "                        isFirst = False\r\n",
    "                        if j is None or j=='':\r\n",
    "                            res = False\r\n",
    "                            break\r\n",
    "                        if j=='0':\r\n",
    "                            res = False\r\n",
    "                            break\r\n",
    "                        elif not isdigit(j):\r\n",
    "                            res = False\r\n",
    "                            break\r\n",
    "                    else:\r\n",
    "                        if not isdigit(j):\r\n",
    "                            res = False\r\n",
    "                            break\r\n",
    "\r\n",
    "                if res:\r\n",
    "                    if i is None or i!='':\r\n",
    "                        if int(i)>255:\r\n",
    "                            res = False\r\n",
    "                            break\r\n",
    "                    elif i=='':\r\n",
    "                        res = False\r\n",
    "                        break\r\n",
    "                else:\r\n",
    "                    if i=='0':\r\n",
    "                        res = True\r\n",
    "                        continue\r\n",
    "                    else :break\r\n",
    "            if tempA<4:\r\n",
    "                return \"Neither\"\r\n",
    "        else:\r\n",
    "            strList = queryIP.split(':')\r\n",
    "            length = len(strList)\r\n",
    "            if length<8:\r\n",
    "                 return \"Neither\"\r\n",
    "\r\n",
    "        if length==8:\r\n",
    "            for i in strList:\r\n",
    "                temp = 0\r\n",
    "                if i=='':\r\n",
    "                    res = False\r\n",
    "                    break\r\n",
    "                for j in i:\r\n",
    "                    if temp>=4:\r\n",
    "                        res = False\r\n",
    "                        break\r\n",
    "                    else:\r\n",
    "                        if (j in alph) or isdigit(j):\r\n",
    "                            res = True\r\n",
    "                            temp+=1\r\n",
    "                        else:\r\n",
    "                            res = False\r\n",
    "                            break\r\n",
    "                if not res:break\r\n",
    "        if res:\r\n",
    "            if length==4:\r\n",
    "                return \"IPv4\"\r\n",
    "            elif length==8:\r\n",
    "                return \"IPv6\"\r\n",
    "            else:\r\n",
    "                return \"Neither\"\r\n",
    "        else:\r\n",
    "            return \"Neither\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, queryIP: str) -> str:\n",
    "        ips = queryIP.split('.')\n",
    "        ip_type = \"Neither\"\n",
    "        if len(ips) == 4:\n",
    "            for ip in ips:\n",
    "                if len(ip) > 1 and ip[0] == '0':\n",
    "                    break\n",
    "                try:\n",
    "                    ip = int(ip)\n",
    "                except:\n",
    "                    break\n",
    "                if ip < 0 or ip > 255:\n",
    "                    break\n",
    "            else:\n",
    "                ip_type = \"IPv4\"\n",
    "\n",
    "        ips = queryIP.split(':')\n",
    "        if len(ips) == 8:\n",
    "            for ip in ips:\n",
    "                if len(ip) > 4:\n",
    "                    break\n",
    "                try:\n",
    "                    ip = int(ip, 16)\n",
    "                except:\n",
    "                    break\n",
    "            else:\n",
    "                ip_type = \"IPv6\"\n",
    "\n",
    "        return ip_type\n",
    "                \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, queryIP: str) -> str:\n",
    "\n",
    "        ipv4 = False\n",
    "        ipv6 = False\n",
    "\n",
    "        if \".\" in queryIP:\n",
    "            ipv4 = True\n",
    "        elif \".\" not in queryIP and \":\" in queryIP:\n",
    "            ipv6 = True\n",
    "        \n",
    "        if ipv4:\n",
    "            arr = queryIP.split(\".\")\n",
    "\n",
    "            if len(arr) != 4:\n",
    "                return \"Neither\"\n",
    "            print(arr)\n",
    "            \n",
    "            for num in arr:\n",
    "                #print(num, num == '')\n",
    "                if num == \"\":\n",
    "                    return \"Neither\"\n",
    "\n",
    "                if not num.isdigit():\n",
    "                    return \"Neither\"\n",
    "\n",
    "                if not 0 <= int(num) <= 255:\n",
    "                    return \"Neither\"\n",
    "                \n",
    "                if num.startswith(\"0\") and len(num) != 1:\n",
    "                    return \"Neither\"\n",
    "                \n",
    "            return \"IPv4\"\n",
    "\n",
    "        elif ipv6:\n",
    "            arr = queryIP.split(\":\")\n",
    "\n",
    "            if len(arr) != 8:\n",
    "                return \"Neither\"\n",
    "\n",
    "            for num in arr:\n",
    "                if not 1 <= len(num) <= 4:\n",
    "                    #print(\"stop\")\n",
    "                    return \"Neither\"\n",
    "            \n",
    "                for char in num:\n",
    "                    if char not in \"1234567890abcdefABCDEF\":\n",
    "                        #print(\"stop\")\n",
    "                        return \"Neither\"\n",
    "                \n",
    "            return \"IPv6\"\n",
    "\n",
    "        #print(\"stop\")\n",
    "        return \"Neither\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def validIPAddress(self, queryIP: str) -> str:\n",
    "        if queryIP.find(\".\") != -1:\n",
    "            # IPv4\n",
    "            last = -1\n",
    "            for i in range(4):\n",
    "                cur = (len(queryIP) if i == 3 else queryIP.find(\".\", last + 1))\n",
    "                if cur == -1:\n",
    "                    return \"Neither\"\n",
    "                if not 1 <= cur - last - 1 <= 3:\n",
    "                    return \"Neither\"\n",
    "                \n",
    "                addr = 0\n",
    "                for j in range(last + 1, cur):\n",
    "                    if not queryIP[j].isdigit():\n",
    "                        return \"Neither\"\n",
    "                    addr = addr * 10 + int(queryIP[j])\n",
    "                \n",
    "                if addr > 255:\n",
    "                    return \"Neither\"\n",
    "                if addr > 0 and queryIP[last + 1] == \"0\":\n",
    "                    return \"Neither\"\n",
    "                if addr == 0 and cur - last - 1 > 1:\n",
    "                    return \"Neither\"\n",
    "                \n",
    "                last = cur\n",
    "            \n",
    "            return \"IPv4\"\n",
    "        else:\n",
    "            # IPv6\n",
    "            last = -1\n",
    "            for i in range(8):\n",
    "                cur = (len(queryIP) if i == 7 else queryIP.find(\":\", last + 1))\n",
    "                if cur == -1:\n",
    "                    return \"Neither\"\n",
    "                if not 1 <= cur - last - 1 <= 4:\n",
    "                    return \"Neither\"\n",
    "\n",
    "                for j in range(last + 1, cur):\n",
    "                    if not queryIP[j].isdigit() and not(\"a\" <= queryIP[j].lower() <= \"f\"):\n",
    "                        return \"Neither\"\n",
    "                \n",
    "                last = cur\n",
    "            \n",
    "            return \"IPv6\"\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
